from django.shortcuts import render
from rest_framework import mixins
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from .models import User
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from .serializers import CreateUserSerializer, AddressSerializer
from rest_framework.permissions import IsAuthenticated
from .serializers import UserCenterInfoSerializer

from rest_framework.decorators import action
from .serializers import AddressTitleSerializer


# Create your views here.
# APIView
# GenericAPIView
# ListAPIView ,CreateAPIView
class RegisterUsernameView(APIView):

    """
    判断用户是否注册

    GET     /users/usernames/(?P<username>\w{5,20})/count/

    POST    序列化器

    我们需要把用户名发送过来, 接收用户,根据用户名进行判断
    用户是否注册


    """

    def get(self,request,username):

        # 通过用户名的个数
        count = User.objects.filter(username=username).count()
        # 组织数据,返回
        context = {
            'count':count,
            'username':username #可选
        }

        return Response(context)


class RegisterMobileView(APIView):
    """
    GET     /users/phones/(?P<mobile>1[345789]\d{9})/count/

    GET     /users/phones/?mobile=xxxxx
    POST    /users/phones/      mobile=xxxxx
    根据用户提交的手机号,判断是否存在该手机号
    """


    def get(self,request,mobile):

        count = User.objects.filter(mobile=mobile).count()

        context = {
            'count':count,
            'mobile':mobile     #可选
        }

        return Response(context)

# APIView
# GenericAPIVIew
# lsitAPIView,CreateAPIView

# 数据需要入库 我们选项 CreateAPIView
class CreateUserView(CreateAPIView):
    """
    实现注册功能

    POST            /uesrs/

    1. 我们把用户名,密码,手机号,短信验证码, 是否同意协议 post给我们
    2. 对数据进行验证
    3. 验证之后 数据入库


    需求分析(功能分析[参数 和 功能]) --> 确定HTTP的请求方式 --> 确定视图继承自谁
    """


    serializer_class = CreateUserSerializer



# 用户中心 个人信息
# class UserCenterInfoView(APIView):
#
#     """
#     GET     /users/infos/
#
#     只有登录用户才可以访问
#     获取用户的信息(获取指定用户信息）
#
#     """
#     permission_classes = [IsAuthenticated]
#
#     def get(self,request):
#
#         serializer = UserCenterInfoSerializer(request.user)
#
#         return Response(serializer.data)

from rest_framework.generics import RetrieveAPIView
class UserCenterInfoView(RetrieveAPIView):

    """
    GET     /users/infos/

    只有登录用户才可以访问
    获取用户的信息(获取指定用户信息）

    """
    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    # 重写 get_object 方法

    def get_object(self):

        return self.request.user


# APIView
# GenericAPIView
# UpdateAPIView

from rest_framework.generics import UpdateAPIView
from .serializers import EmailSerializer
class EmailView(UpdateAPIView):

    """
    1.当用户点击确定按钮的时候，把 邮箱 发送给后台 邮箱需要校验
    2.更新 用户的邮箱信息
    3.发送一个激活邮件（链接）
    4.激活链接如何实现
    5.邮件如何发送
    6.邮件采用celery异步发送
    """

    permission_classes = [IsAuthenticated]

    serializer_class = EmailSerializer

    def get_object(self):

        return self.request.user


# from django.core.mail import send_mail
"""

subject 邮件标题
message 普通邮件正文， 普通字符串
from_email 发件人
recipient_list 收件人列表
html_message 多媒体邮件正文，可以是html字符串

"""

# send_mail(subject,message,from_email,recipient_list,html_message=None)


class VerificationEmailView(APIView):
    """
    验证激活邮箱
    GET /users/emails/verification/?token=xxxx

    思路:
    获取token,并判断
    获取 token中的id
    查询用户,并判断是否存在
    修改状态
    返回响应
    """
    def get(self,request):

        # 获取token 并判断
        token = request.query_params.get('token')

        if token is None:

            return Response(status=status.HTTP_400_BAD_REQUEST)

        user = User.check_verify_token(token)

        if user is None:

            return Response(status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True

        user.save()

        return Response({'message':'ok'})


class AddressViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    #制定序列化器
    serializer_class = AddressSerializer
    #添加用户权限
    permission_classes = [IsAuthenticated]
    #由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset,many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id':user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self,request,*args,**kwargs):
        """
                处理删除
                """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)



    @action(methods=['put'],detail=True)

    def title(self,request,pk=None,address_id=None):
        """
        修改标题
        :param self:
        :param request:
        :param pk:
        :param address_id:
        :return:
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)
